import { ElTag, type TagProps } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import {
  WARNING_WORK_ORDER_STATES_TEXT,
  calculateTheLastTime,
  joinThresoldValue,
  joinWarningValue,
} from './helper'
import { useWarningList } from './MixinWarningList'
import { uuid } from '@/utils'
import { PAGE_SIZES } from '@/constant/modules/paging'
import type { MyWorkOrder, TableColumn } from '@/types'
import { alarmApi } from '@/api'

import { WARNING_WORK_ORDER_STATES } from '@/enum'

/**
 * @mixin 我的工单列表
 */
export function useMyWorkOrders() {
  const [loading, setLoading] = useState(true)
  const [lists, setLists] = useShallowState<MyWorkOrder[]>(
    [],
  )
  const { columns: _columns } = useWarningList()
  const warningListColumns = cloneDeep(toRaw(_columns))
  // 替换 告警状态 为 期望处理结束时间
  warningListColumns.splice(8, 0, {
    key: uuid(),
    label: '期望处理结束时间',
    prop: 'processingEndTime',
    width: 180,
  })

  //  告警结束时间
  warningListColumns.splice(14, 0, {
    key: uuid(),
    label: '告警结束时间',
    prop: 'warningEndTime',
    width: 160,
  })

  // 替换 工单号 为 创建时间
  warningListColumns.splice(
    warningListColumns.length - 1,
    1,
    {
      key: uuid(),
      label: '创建时间',
      prop: 'creationTime',
      width: 160,
    },
  )

  // console.log(warningListColumns);

  const columns: TableColumn<MyWorkOrder>[] = reactive([
    {
      key: uuid(),
      label: '工单号',
      prop: 'workOrderNum',
      width: 180,
    },
    {
      key: uuid(),
      label: '工单状态',
      prop: 'orderState',
      width: 110,
      render({ row }) {
        return renderOrderState(row as MyWorkOrder)
      },
    },
    ...warningListColumns,
  ])

  /**
   * 修改 告警持续时间的算法
   * @description “已处理”的工单 告警持续时间 = 告警结束时间 - 告警开始时间
   * @description 非“已处理”的工单 告警持续时间 = 当前时间 - 告警开始时间
   */
  const target = columns.find(
    v => v.prop === 'warningLastTime',
  )
  if (target) {
    // target.hidden = true
    target.render = ({ row }) =>
      h(
        'span',
        calculateTheLastTime(
          row.warningStartTime,
          row.orderState
          === WARNING_WORK_ORDER_STATES.SOLVED
            ? row.warningEndTime
            : undefined,
        ),
      )
  }

  const pagination = reactive({
    pageNumber: 1,
    pageSize: PAGE_SIZES[0]!,
    total: 0,
  })

  async function getLists(
    paramsFn: (
      pageNumber: number,
      pageSize: number
    ) => alarmApi.SelectWarningWorkOrderByUserParams,
  ) {
    setLoading(true)
    const { pageNumber, pageSize } = pagination
    const params = paramsFn(pageNumber, pageSize)
    try {
      const { data }
        = await alarmApi.selectWarningWorkOrderByUser(params)
      data.records?.forEach((v) => {
        // 阈值上下限
        v.thresholdValue = joinThresoldValue(
          v.thresholdValueUp,
          v.thresholdValueDown,
          v.unit,
        )
        // 监测值（带单位）
        v.warningValue = joinWarningValue(
          +v.warningValue,
          v.unit,
        )
        // 工单状态
        v.orderState = v.workOrderState
      })
      setLists(data.records || [])
      pagination.total = data.total
    }
    catch (e) {
    }
    finally {
      setLoading(false)
    }
  }

  async function handleDownload(
    paramsFn: (
      pageNumber: number,
      pageSize: number
    ) => alarmApi.SelectWarningWorkOrderByUserParams,
  ) {
    const { pageNumber, pageSize } = pagination
    const params = paramsFn(pageNumber, pageSize)
    try {
      const { data } = await alarmApi.exportWarningWorkOrder(params)
      window.open(data?.url)
    }
    catch (e) {}
  }

  return {
    loading,
    lists,
    pagination,
    columns,

    setLoading,
    getLists,
    handleDownload,
  }
}

export function renderOrderState(row: MyWorkOrder) {
  // @ts-expect-error
  if (row.orderState === '' || row.orderState === null)
    return h('span')
  const level = +row.orderState
  return h(
    ElTag,
    {
      // 状态(0-待处理，1-待审核，2-已处理，3-驳回)
      type: ['warning', 'primary', 'success', 'danger'][
        level
      ] as TagProps['type'],
    },
    () =>
      [
        WARNING_WORK_ORDER_STATES_TEXT.UNSETTLED,
        WARNING_WORK_ORDER_STATES_TEXT.PENDING,
        WARNING_WORK_ORDER_STATES_TEXT.SOLVED,
        WARNING_WORK_ORDER_STATES_TEXT.REJECTED,
      ][level],
  )
}
